package lxy.contacttest.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dengdayi
 * Date: 2016/06/22 16：30
 * 手机本地通讯录帮助类
 */
public class PhoneContactUtils {
    /**
     * 获取手机通讯录列表
     *
     * @param context
     * @return
     */
    public static List<ContactBean> getContactList(Context context) {
        Cursor rawContacts = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
                new String[]{ContactsContract.RawContacts._ID}, null, null, null);

        List<ContactBean> beans = new ArrayList<>();

        while (rawContacts.moveToNext()) {
            int raw_id = rawContacts.getInt(0);
            Cursor dataContacts = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null,
                    ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{raw_id + ""},
                    null);
            beans.add(getLocalContactById(String.valueOf(raw_id), dataContacts));
        }
        return beans;
    }

    /**
     * 根据ID获单个的通讯录中联系了信息
     *
     * @param dataContacts
     * @return
     */
    public static ContactBean getLocalContactById(String contactId, Cursor dataContacts) {
        ContactBean contactInfo = null;
        while (dataContacts.moveToNext()) {
            String data1 = dataContacts.getString(dataContacts
                    .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DATA1));

            int data2 = dataContacts.getInt(dataContacts
                    .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DATA2));

            String mimetype = dataContacts.getString(dataContacts
                    .getColumnIndex(ContactsContract.Data.MIMETYPE));
            if (contactInfo == null) {
                contactInfo = new ContactBean(null);
                contactInfo.setContact_id(contactId);
            }
            if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mimetype)) {
                contactInfo.setName(data1);
            }
            if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {
                List<PhoneBean> phoneList = null;
                if (contactInfo.getPhones().size() > 0) {
                    phoneList = contactInfo.getPhones();
                } else {
                    phoneList = new ArrayList<>();
                }

                if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == data2) {
                    PhoneBean info = new PhoneBean();
                    info.setNumber(data1);
                    phoneList.add(info);
                }
                contactInfo.setPhones(phoneList);
            }
            if (ContactsContract.CommonDataKinds.Email.MIMETYPE.equals(mimetype)) {
                List<EmailBean> emailList = null;
                if (contactInfo.getEmails().size() > 0) {
                    emailList = new ArrayList<>();
                } else {
                    emailList = new ArrayList<>();
                }
                EmailBean email = new EmailBean();
                email.setEmail(data1);
                contactInfo.setEmails(emailList);
            }
        }
        return contactInfo;
    }

    /**
     * 通过名字获取手机联系人id
     *
     * @param context
     * @param name:姓名
     * @return
     */

    public static String getRawId(Context context, String name) {
        // 获取联系人的所需信息
        Cursor cur = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.DISPLAY_NAME + "=?", new String[]{name},
                null);
        if (cur.moveToFirst()) {
            // 获取联系人id号
            String contact_id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            return contact_id;
        }
        cur.close();
        return "";
    }

    /**
     * 通过联系人id获取手机号，（手机类型为 TYPE_MOBILE）
     *
     * @param context
     * @param contact_id
     * @return
     */
    public static List<PhoneBean> getContactPhoneList(Context context, String contact_id) {
        List<PhoneBean> phoneBeans = new ArrayList<>();
        if (TextUtils.isEmpty(contact_id)) {
            return phoneBeans;
        }
        Cursor phoneCursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contact_id,
                null, null);

        while (phoneCursor.moveToNext()) {

            int raw_id = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName._ID));
            String number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            int type = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

            if (!TextUtils.isEmpty(number)) {
                number = number.replaceAll("[^0-9]", "");//只保留数据
                if (number.length() >= 3) {
                    String str = number.substring(0, 2);
                    if ("86".equals(str)) {
                        number = number.substring(2, number.length());
                    }
                    //说明电话类型是手机
                    if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == type) {
                        PhoneBean bean = new PhoneBean(raw_id, number, type);
                        phoneBeans.add(bean);
                    }
                }
            }


        }
        phoneCursor.close();
        return phoneBeans;
    }

    /**
     * 通过联系人id获取邮箱，（类型为 TYPE_WORK）
     *
     * @param context
     * @param contact_id
     * @return
     */
    public static List<EmailBean> getContactEmailList(Context context, String contact_id) {
        List<EmailBean> emailBeans = new ArrayList<>();
        if (TextUtils.isEmpty(contact_id)) {
            return emailBeans;
        }
        // 查找邮箱
        Cursor emailCursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contact_id,
                null, null);

        while (emailCursor.moveToNext()) {
            int raw_id = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
            String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            if (!TextUtils.isEmpty(email)) {
//                if (ContactsContract.CommonDataKinds.Email.TYPE_WORK == type) {
                EmailBean bean = new EmailBean(raw_id, email, type);
                emailBeans.add(bean);
//                }
            }
        }
        emailCursor.close();
        return emailBeans;
    }

    /**
     * 向手机中录入联系人信息
     *
     * @param info 要录入的联系人信息
     */
    public static void addContacts(Context context, ContactBean info, int contact_id) {

        ContentValues values = new ContentValues();
        // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        long rawContactId = contact_id;
        if (rawContactId < 0) {
            Uri rawContactUri = context.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
            rawContactId = ContentUris.parseId(rawContactUri);
        }
        // 往data表入姓名数据
        insertUserName(context, values, rawContactId, info.getName());

        // 录入联系电话
        List<PhoneBean> phoneList = info.getPhones();
        for (PhoneBean phoneInfo : phoneList) {
            insertMobile(context, values, rawContactId, phoneInfo.getNumber());
        }

        // 录入联系人邮箱信息
        List<EmailBean> emailList = info.getEmails();
        for (EmailBean email : emailList) {
            insertEmail(context, values, rawContactId, email.getEmail());
        }
    }

    /**
     * 更新用户邮箱信息
     *
     * @param context
     * @param contactId:联系人id
     * @param dataId：data表中的id
     * @param email:邮箱名字
     */
    public static void updateUserEmail(Context context, String contactId, int dataId, String email) {
        if (dataId == -1) {
            //不存在此邮箱，插入数据
            ContentValues values = new ContentValues();
            insertEmail(context, values, Integer.parseInt(contactId), email);
        } else {
            //存在此邮箱，更新操作
            updateUserData(context, dataId, email, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
        }
    }

    /**
     * 更新用户电话信息
     *
     * @param context
     */
    public static void updateUserMobile(Context context, String contactId, int dataId, String mobile) {
        if (dataId == -1) {
            //不存在此电话号码，插入数据
            ContentValues values = new ContentValues();
            insertMobile(context, values, Integer.parseInt(contactId), mobile);
        } else {
            //存在此电话，更新操作
            updateUserData(context, dataId, mobile, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        }
    }

    /**
     * 删除联系人表中的数据
     *
     * @param context
     * @param contactId
     */
    public static void deleteContact(Context context, String contactId) {
        if (!TextUtils.isEmpty(contactId)) {
            //说明存在，删除数据
            ContentResolver resolver = context.getContentResolver();
            resolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + "=?", new String[]{contactId});
        }
    }

    /**
     * 删除data表中的数据
     *
     * @param context
     * @param dataId
     */
    public static void deleteUserData(Context context, int dataId) {
        if (dataId != -1) {
            //说明存在，删除数据
            ContentResolver resolver = context.getContentResolver();
            resolver.delete(ContactsContract.Data.CONTENT_URI, ContactsContract.CommonDataKinds.StructuredName._ID + "=?", new String[]{String.valueOf(dataId)});
        }
    }

    /**
     * 更新data表中的数据
     *
     * @param context
     * @param dataId
     * @param dataText
     */
    private static void updateUserData(Context context, int dataId, String dataText, int type) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(ContactsContract.Data.DATA1, dataText);
        values.put(ContactsContract.Data.DATA2, type);
        resolver.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.CommonDataKinds.StructuredName._ID + "=?", new String[]{String.valueOf(dataId)});
        values.clear();
    }

    /**
     * 插入data表中数据
     *
     * @param context
     * @param contactId
     * @param dataText
     * @param mimeType
     * @param type
     */
    private static void insertUserData(Context context, ContentValues values, long contactId, String dataText, String mimeType, int type) {
        //录入电话
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, contactId);
        values.put(ContactsContract.RawContacts.Data.MIMETYPE, mimeType);
        // 设置录入联系人电话信息
        values.put(ContactsContract.Data.DATA1, dataText);
        if (type != -1) {
            values.put(ContactsContract.Data.DATA2, type);
        }
        // 往data表入电话数据
        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();
    }


    /**
     * data表中插入电话号码
     *
     * @param context
     * @param contactId
     * @param mobile
     */
    private static void insertMobile(Context context, ContentValues values, long contactId, String mobile) {
        insertUserData(context, values, contactId, mobile,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
    }

    /**
     * data表中插入邮箱
     *
     * @param context
     * @param contactId
     * @param email
     */
    private static void insertEmail(Context context, ContentValues values, long contactId, String email) {
        insertUserData(context, values, contactId, email,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                ContactsContract.CommonDataKinds.Email.TYPE_WORK);
    }

    /**
     * data表中插入联系人名字
     *
     * @param context
     * @param contactId
     * @param name
     */
    private static void insertUserName(Context context, ContentValues values, long contactId, String name) {
        insertUserData(context, values, contactId, name, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, -1);
    }

}
